package com.idea.relax.redis.support.proto;

import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.Schema;
import io.protostuff.runtime.RuntimeSchema;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.util.Objects;

/**
 * 增加ProtoStuff序列化方式，生成的码流比jdk序列化小，速度更快
 **/
public class ProtoStuffSerializer implements RedisSerializer<Object> {

    private final Schema<ProtoWrapper> schema;

    private final LinkedBuffer buffer;

    public ProtoStuffSerializer() {
        this.schema = RuntimeSchema.getSchema(ProtoWrapper.class);
        this.buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
    }

    @Override
    public byte[] serialize(Object t) throws SerializationException {
        if (t == null) {
            return new byte[0];
        }
        try {
            ProtoWrapper<Object> wrapper = new ProtoWrapper<>(t);
            return ProtostuffIOUtil.toByteArray(wrapper, schema, buffer);
        } finally {
            buffer.clear();
        }
    }

    @Override
    public Object deserialize(byte[] bytes) throws SerializationException {
        if (Objects.isNull(bytes)) {
            return null;
        }
        ProtoWrapper<Object> wrapper = schema.newMessage();
        ProtostuffIOUtil.mergeFrom(bytes, wrapper, schema);
        return wrapper.getValue();
    }

}
